﻿using B.X.Rabbit.Domain.RBAC;
using B.X.Rabbit.Infrastructure.IReponsitory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace B.X.Rabbit.Infrastructure.Reponsitory
{
    public class RoleRepository : BaseReponsitory<Role>, IRoleRepository
    {
        private readonly MainDbContext rbacContext;
        private readonly ILogger<RoleRepository> logger;
        public RoleRepository(MainDbContext context, ILogger<RoleRepository> logger) : base(context, logger)
        {
            this.rbacContext = context;
            this.logger = logger;
        }
        public async Task<bool> RolePermissInsert(Role info, int[] permissIds)
        {
            try
            {
                var res = false;
                var sponce = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    var rolePermiss = await rbacContext.Roles.AddAsync(info);
                    await rbacContext.SaveChangesAsync();
                    //添加角色权限
                    foreach (var permissId in permissIds)
                    {
                        await rbacContext.RolePermissions.AddAsync(new RolePermission()
                        {
                            RoleId = rolePermiss.Entity.RoleId,
                            PermissionId = permissId
                        });

                    }
                    await rbacContext.SaveChangesAsync();
                    sponce.Complete();
                    res = true;
                    return res;
                }
                finally
                {
                    //事务回滚
                    sponce.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "事务添加角色权限失败");
                return false;
            }
        }
    }
}
